<template>
  <a-card class="general-card" title="商品列表" :bordered="false">
    <a-tabs @change="changeGoodsStatus" :default-active-key="goodsStatusVar">
      <a-tab-pane key="ALL" title="全部"></a-tab-pane>
      <a-tab-pane key="UPPER" title="售卖中"></a-tab-pane>
      <a-tab-pane key="DOWN" title="已下架"></a-tab-pane>
      <a-tab-pane key="TOBEAUDITED" :title="'审核中'"></a-tab-pane>
      <a-tab-pane key="REFUSE" :title="'审核驳回'"></a-tab-pane>
      <a-tab-pane key="PASS" title="审核通过"></a-tab-pane>
    </a-tabs>
    <PickSearchColumn :rowSpan="isNormal ? 0 : 12" :columns="columnsSearch" @reset="(val) => {apiParams = {...apiParams, ...val}}" @search="(val) => {apiParams = {...apiParams, ...val}}">
    </PickSearchColumn>
    <a-row style="margin-bottom: 16px" v-if="isNormal">
      <a-button type="primary" @click="deleteAll">批量删除</a-button>
    </a-row>
    <PickTablePage @selectTableChange="chosenGoods" :checkbox="true" :radio="isNormal ? false : true" ref="tablePageRef" :pageSize="isNormal ? 10 : 6"  :columns="columnsTable" :methods="sortMethods" :bordered="true" :api="isNormal ? getGoodsListDataSeller : getGoodsSkuData"
      @update="handleEdit" :api-params="apiParams" >
      <template #btnList="{ data }">
        <a-space>
          <a-button v-if="data?.marketEnable == 'DOWN'"  @click="upper(data)" type="text" status="success">上架</a-button>
          <a-button v-else  @click="soldOut(data)" type="text" status="danger">下架</a-button>
          <a-button  @click="$openWindow({ name: 'goodsdetail', query: { id: data.id }, })" type="text" status="success">查看</a-button>
        </a-space>
      </template> 
    </PickTablePage>
    <!-- 下架modal -->
    <a-modal v-model:visible="underForm.enableAddModal" :align-center="false" :footer="false">
      <template #title> 下架操作 </template>
      <a-form ref="formRef" :model="underForm.form" @submit="handleAddOk">
        <a-form-item field="reason" label="下架原因" :rules="[REQUIRED, VARCHAR20]" :validate-trigger="['change']">
          <a-input v-model="underForm.form.reason" />
        </a-form-item>
        <a-form-item label="操作">
          <a-button :loading="underForm.formLoading" html-type="submit" type="primary">保存</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
import { deleteGoods, getGoodsListDataSeller, getGoodsSkuData, lowGoods, upGoods } from '@/api/goods';
import { PickSearchColumn, PickTablePage } from '@pickmall/ui-v3-components';

import useCurrentInstance from '@/hooks/useCurrentInstance';
import { usePathJumpStore } from '@/store/index';
import { ColumnsDataRule, MethodsRule, SearchRule } from '@/types/global';
import { authFlag, goodsType, marketEnable, salesModel } from '@/utils/tools';
import { REQUIRED, VARCHAR20 } from '@/utils/validator';
import { Message } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

const goodsStatusVar = ref<string>('UPPER')
const apiParams = ref<any>({
  authFlag: 'PASS',
  goodsStatus: goodsStatusVar.value,
})
// 获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
const store = usePathJumpStore()
const tablePageRef = ref<any>();
const router = useRouter();
const formRef = ref<FormInstance>();
const selectList = ref([]); // 多选数据
const ids = ref<string>(''); // 多选行id
// 组件模式
const props = defineProps({
  templateModel: {
    type: String,
    default: 'normal',
  },
})
const isNormal: boolean = props.templateModel === 'normal';

interface formInterface {
  enableAddModal: boolean;
  formLoading: boolean;
  fid: string | number;
  form: {
    reason: string;
    [key:string]: any;
  };
  [key:string]: any;
}

const columnsSearch: Array<SearchRule> = [
  {
    label: '商品名称',
    model: 'goodsName',
    disabled: false,
    input: true,
  },
  {
    label: '店铺名称',
    model: 'storeName',
    disabled: false,
    input: true,
  },

  {
    label: '销售模式',
    model: 'salesModel',
    disabled: false,
    select: {
      options: salesModel,
    },
  },
  {
    label: '商品类型',
    model: 'goodsType',
    disabled: false,

    select: {
      options: goodsType,
    },
  },
];

const columnsTable: ColumnsDataRule[] = [
  {
    title: '商品名称',
    dataIndex: 'goodsName',
    slot: true,
    ellipsis: false,
    width:  isNormal ? 300 : 250,
    slotData: {
      goods: {
        goodsName: 'goodsName',
        goodsImage: 'original',
        goodsId: 'goodsId',
        skuId: 'skuId',
        linkTo: true
      },
    },
  },

  {
    title: '销售模式',
    dataIndex: 'salesModel',
    slot: true,
    slotData: {
      badge: salesModel,
    },
  },
  {
    title: '商品类型',
    dataIndex: 'goodsType',
    slot: true,
    slotData: {
      badge: goodsType,
    },
  },
  {
    title: '商品价格',
    dataIndex: 'price',
    currency: true,
  },
  {
    title: '店铺名称',
    dataIndex: 'storeName',
  },
  {
    title: '库存',
    dataIndex: 'quantity',
  },
  {
    title: '审核状态',
    dataIndex: 'authFlag',
    slot: true,
    slotData: {
      badge: authFlag,
    },
  },
  {
    title: '上架状态',
    dataIndex: 'marketEnable',
    slot: true,
    slotData: {
      badge: marketEnable,
    },
  },
];

const sortMethods: any = isNormal ? {
  title: '操作',
  width: 250,
  fixed: 'right',
  methods: [
    {
      slot: true,
      slotTemplate: 'btnList',
    },
  ],
} : {};
// 数据集
const underForm = reactive<formInterface>({
  enableAddModal: false,
  formLoading: false,
  fid: '', // 当前form的ids
  form: {
    reason: '',
  }, // 表单提交数据
});
const emit = defineEmits(['selectTableChange']);


// 单选商品的回调方法
function chosenGoods(val: any) {
  emit('selectTableChange', { ...val[0], ___type: 'goods' })
  selectList.value = val
}

// 点击修改
function handleEdit(val: any) {
  if (val) {
    Object.keys(val.record).forEach((key) => {
      // eslint-disable-next-line no-unused-expressions,no-prototype-builtins
      underForm.form.hasOwnProperty(key)
        ? (underForm.form[key] = val.record[key])
        : '';
    });
    underForm.form.reason = val.record.reason;
    underForm.fid = val.record.id;
    underForm.enableAddModal = true;
  }
}
const soldOut = (v:any) => {
  underForm.form.reason = ""
  underForm.fid = v.id
  underForm.enableAddModal = true;
}
async function handleAddOk() {
  const auth = await formRef.value?.validate();
    if (!auth) {
      lowGoods(underForm.fid, underForm.form).then((res)=>{
        if(res.data.success){
          Message.success('操作成功');
          underForm.enableAddModal = false;
          tablePageRef.value.init();
        }
      })
  }
}
// 上架
const upper = (data:any) => {
  modal.confirm({
    title: '确认上架',
    content: `您确认要上架${data.goodsName}?`,
    alignCenter: false,
    onOk: async () => {
      const res = await upGoods(data.id);
      if (res.data.success) {
        Message.success('上架成功');
        tablePageRef.value.init();
      }
    },
  });
}

// 批量删除
const deleteAll = () => {
  if (selectList.value.length <= 0) {
    Message.error('您还未选择要删除的商品');
    return;
  }
  selectList.value.forEach((item: any) => {
    ids.value += `${item.id},`;
  });
  const joinId = ids.value.substring(0, ids.value.length - 1);
  modal.confirm({
    title: '确认删除',
    content: `您确定要删除所选的${selectList.value.length}个商品`,
    alignCenter: false,
    onOk: async () => {
      const res = await deleteGoods({ goodsId: joinId });
      if (res.data.success) {
        Message.success('删除成功');
        tablePageRef.value.init();
      }
    },
  });
};

// 切换状态
function changeGoodsStatus(val: string) {
  apiParams.value.goodsStatus = val
  if (val === 'UPPER') {
    apiParams.value.authFlag = 'PASS'
  }
  else {
    apiParams.value.authFlag = ''
  }
}

</script>
